package com.cqgc.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.burial.common.log.MyLog;
import com.cqgc.entity.Result;
import com.cqgc.entity.User;
import com.cqgc.mapper.UserMapper;
import com.cqgc.service.UserService;
import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
@Transactional
public class UserController {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    //得到登录者角色
    public int getLogonRole(String rawToken){

        String token = rawToken.startsWith("Bearer ") ? rawToken.substring(7) : rawToken; // 移除"Bearer "前缀
        DecodedJWT decodedJWT = JWT.decode(token);//解析token
        String loginrole = decodedJWT.getClaim("role").asString();//找到token中登录者的role
        int role1;//登录者的role
        switch (loginrole) {
            case "管理员":
                role1 = 1;
                break;
            case "供应商":
                role1 = 2;
                break;
            case "采购方":
                role1 = 3;
                break;
            default:
                throw new IllegalArgumentException("Unknown role: " + loginrole);
        }
        return role1;
    }


    //根据状态和账号分页查询用户信息
    //当state为null时，role为null时，条件只有page，即查询所有
    @PostMapping("/findlist")
    @ApiOperation("分页查询")
    @MyLog(type = "用户信息检索", msg = "检索用户信息")
    public Result findList(Optional<Integer> state, Optional<Integer> role,
                           HttpServletRequest request,
                           @RequestBody com.cqgc.entity.Page page0) {

        String rawToken = request.getHeader("Authorization");
        if (rawToken == null) {
            return Result.error("没有登录者信息");
        }
        if (page0 == null) {
            page0.setPageSize(5);
            page0.setCurrentPage(1);

        }
        int role1=getLogonRole(rawToken);

        Integer roleId = role.orElse(0);// 如果 role 参数为空，则设置为 null
        Integer state1 = state.orElse(0);// 如果 state 参数为空，则设置为 null
        Page<User> userPage = userService.findUsersByStatus(state1, role1, roleId, page0);


        if (userPage.getRecords() != null) {
            return Result.success(userPage);
        } else {
            return Result.error("没有数据");
        }
    }


    //根据id查询
    @PostMapping("/findid")
    @ApiOperation("根据id查找信息")
    @MyLog(type = "用户信息检索", msg = "根据用户id检索用户的信息")
    public Result findById(Integer id) {

        if (id == 0) {
            Result.error("请输入正确id");
        }
        User user = userMapper.selectById(id);
        if (user != null) {
            return Result.success(user);
        } else {
            return Result.error("未查询到该用户");
        }
    }


    //通过id修改状态，修改state=-1 or 1
    @PostMapping("/batchDelete")
    @ApiOperation("批量删除账号")
    @MyLog(type = "用户信息更新", msg = "删除多个账号")
//    public Result batchUpdateState(@RequestBody User[] users) {
        public Result batchUpdateState(String[] uidStrs) {
//        int[] uids = new int[users.length];
//        for (int i = 0; i < users.length; i++) {
//            uids[i] = users[i].getUid();
//            System.out.println(uids[i]);
//        }
//        System.out.println(uids);
//        String[] uidStrs = Arrays.stream(uids)
//                .mapToObj(String::valueOf)
//                .toArray(String[]::new);
        if (uidStrs != null) {
            UpdateWrapper<User> updateWrapper = Wrappers.update();
            updateWrapper.in("uid",uidStrs)
                    .eq("state", 1)
                    .set("state", -1);
//                    .or()
//                    .ne("state", 1)
//                    .set("state", 1);

            int result = userMapper.update(null, updateWrapper);
            if (result>0){
                return Result.success();
            }else {
                return Result.error("批量删除出错123");
            }
        } else {
            return Result.error("批量删除出错");
        }
    }

    //得到登录用户信息
    @PostMapping("/account")
    @ApiOperation("得到登录者信息")
    @MyLog(type = "登录用户信息检索", msg = "根据token得到登录用户的信息")
    public Result findByAccount(HttpServletRequest request) {
        String rawToken = request.getHeader("Authorization");
        if (rawToken == null) {
            return Result.error("没有登录者信息");
        }
        String token = rawToken.startsWith("Bearer ") ? rawToken.substring(7) : rawToken; // 移除"Bearer "前缀
        DecodedJWT decodedJWT = JWT.decode(token);//解析token
        String loginaccount = decodedJWT.getClaim("account").asString();
        User user = userService.findByAccount(loginaccount);

        return Result.success(user);
    }

    //根据公司名查询-模糊查询
    @PostMapping("/findnamefuzzy")
    @ApiOperation("根据公司名查询-模糊")
    @MyLog(type = "公司信息检索", msg = "根据公司的名称检索公司信息")
    public Result findByUsername(String username, HttpServletRequest request,
                                 @RequestBody com.cqgc.entity.Page page) {
        String rawToken = request.getHeader("Authorization");
        if (rawToken == null) {
            return Result.error("没有登录者信息");
        }
        if (page == null) {
            page.setPageSize(5);
            page.setCurrentPage(1);

        }
        int role=getLogonRole(rawToken);

        if (username.equals("")) {
            return Result.error("请输入正确公司名");
        }
        IPage<User> userPage = userService.findByUsername(username, page, role);

        if (userPage != null) {
            return Result.success(userPage);
        } else {
            return Result.error("没有数据");
        }
    }

//    //根据公司名查询-精确查询
//    @PostMapping("/findnameprecise")
//    @ApiOperation("根据公司名查询-精确")
//    @MyLog(type = "公司信息检索-精确", msg = "根据公司的名称检索公司信息")
//    public Result findByName(String username) {
//
//        if (username.equals("")) {
//            return Result.error("请输入正确公司名");
//        }
//        User user = userService.findByName(username);
//        if (user != null) {
//            return Result.success(user);
//        } else {
//            return Result.error("没有数据");
//        }
//
//    }


    //增加角色,默认state为1
    @PostMapping("/add")
    @ApiOperation("新增账号")
    @MyLog(type = "用户信息更新", msg = "添加一个账号")
    public Result addUser(@RequestBody User user) {

        if (user == null) {
            return Result.error("新增用户不应该为空");
        }
        user.setState(1);
        int insert = userMapper.insert(user);

        if (insert != 0) {
            return Result.success();
        } else {
            return Result.error("新增失败");
        }
    }


    //通过id修改状态，修改state=-1 or 1
    @PostMapping("/delete")
    @ApiOperation("删除账号")
    @MyLog(type = "用户信息更新", msg = "删除一个账号")
    public Result delete(@RequestBody User user) {
        int uid = user.getUid();
        if (uid == 0) {
            return Result.error("请输入id");
        }

        boolean b = userService.deleteById(uid);
        System.out.println(b);
        if (b) {
            return Result.success();
        } else {
            return Result.error("操作失败");
        }
    }

    //修改用户信息
    @PostMapping("/update")
    @ApiOperation("修改账号信息")
    @MyLog(type = "用户信息更新", msg = "修改账号的信息")
    public Result updateById(@RequestBody User user) {
        if (user == null) {
            return Result.error("用户不应该为空");
        }

        boolean b = userService.updateById(user);
        if (b) {
            return Result.success();
        } else {
            return Result.error("修改失败");
        }
    }


}
